/********************************************************************************
*Class:  AddMonthlyCooperationPlanControl
*Method: NewRecord(),Save()
*Useage: Control page AddMonthlyCooperationPlan, user can create Monthly Cooperation Plan on this page.
*Notice: If the record existed, this page will give a warning "******已存在".
********************************************************************************/

public with sharing class AddMonthlyCooperationPlanControl{

    public List<AddMonthlyCooperationRecordItemControl> RecordList{get;set;}
    public List<Hospital__c> HospitalList{get;set;}
    public String msg{get;set;}
    public List<monthly_cooperation_plan_with_hospital__c> mcpwhList{get;set;}
    public Boolean Overdate{get;set;}   
    
    
    private final ApexPages.StandardController controller;  
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
           }  
        set;
    }
    
    public AddMonthlyCooperationPlanControl(ApexPages.StandardController controller)
    {
        Overdate = false; 
        Boolean jumpFlag = false;
        msg = null;
    
        //create the recoed name 
        Date Dtoday = Date.today();
        Integer Iday = Dtoday.day();
        Integer Imonth = Dtoday.month();
        if(Dtoday.month() == 12){
            Imonth = 1;
        }
        else{
             Imonth = Dtoday.month() + 1;
        }
           
        Integer Iyear = Dtoday.year();
        if(Dtoday.month() == 12){ 
            Iyear++;
        }
        String Smonth = String.valueOf(Imonth);
        
        String Syear = String.valueOf(Iyear);
            
        if(RecordList==null)
            RecordList=new List<AddMonthlyCooperationRecordItemControl>();
        else     
            RecordList.clear();
            
        HospitalList = [select Active__c,class__c, Id, Name,effectivedate__c,classchangeto__c,approvalstatus__c,approvaltype__c from Hospital__c where  (OwnerId  =: UserInfo.getUserId() and Active__c =: true)
            or  (OwnerId  =: UserInfo.getUserId() and Active__c =: false and effectivedate__c <: date.today().addmonths(2).tostartofmonth())
             or (OwnerId  !=: UserInfo.getUserId() and effectivedate__c <: date.today().addmonths(2).tostartofmonth()) ];//get current user's hospital list
        List<monthly_cooperation_plan_with_hospital__c> haveRecordList = [select DaysOfRotation__c,Hospital__c,
                                                                hospital_class__c,FlagHospital__c,EFM_Rotation__c,Display__c,
                                                                Name,Id from monthly_cooperation_plan_with_hospital__c 
                                                                where OwnerId  =: UserInfo.getUserId() and Month__c =: Imonth and Year__c =: Syear];        
        //create the record items       
        for(Hospital__c pl:HospitalList)       
        {
            jumpFlag = false;
            if( (pl.active__c==false && (pl.effectivedate__c>=date.today().addmonths(2).tostartofmonth() || pl.effectivedate__c ==null)) || (pl.approvaltype__c=='删除医院' && pl.effectivedate__c<date.today().addmonths(1).tostartofmonth()   )  ){
                continue;
            }
            String RecordName = pl.Name + Syear + '年'+ Smonth + '月填报';

            for(monthly_cooperation_plan_with_hospital__c existRecord : haveRecordList)
            {
                if(existRecord.Hospital__c == pl.id){
                    AddMonthlyCooperationRecordItemControl existItem = new AddMonthlyCooperationRecordItemControl (existRecord);
                    existItem.FhIsCheck = existRecord.FlagHospital__c;
                    existItem.SsyIsCheck= existRecord.EFM_Rotation__c;
                    existItem.DisIsCheck= existRecord.Display__c;
                    existItem.DorIsCheck= existRecord.DaysOfRotation__c;
                    existItem.haveRecord = true;                   
                    RecordList.add(existItem);
                    jumpFlag = true;
                }
            }
            if(jumpFlag == true){
                continue;
            }
            
            monthly_cooperation_plan_with_hospital__c addPlan = new monthly_cooperation_plan_with_hospital__c();
            addPlan.Hospital__c = pl.Id;
            if((pl.approvaltype__c == '改变MSR')&&(pl.approvalstatus__c == '审批通过但未生效')&&(pl.effectivedate__c<Date.today().addMonths(2).toStartOfMonth()))
            {
                continue;
            }
            if((pl.approvaltype__c == '改变医院等级')&&(pl.approvalstatus__c == '审批通过但未生效')&&(pl.effectivedate__c<Date.today().addMonths(2).toStartOfMonth())){
                hospital_approve__c HospitalApproval = [select Active__c,class__c, Id, Name,effectivedate__c,classchangeto__c,approvalstatus__c,approvaltype__c from hospital_approve__c where hospital__c =: pl.id];//get current user's hospital list
                addPlan.hospital_class__c = HospitalApproval.classchangeto__c; 
            }
            else{
                addPlan.hospital_class__c = pl.class__c; 
            }
            AddMonthlyCooperationRecordItemControl addItem = new AddMonthlyCooperationRecordItemControl (addPlan);   
            RecordList.add(addItem);           
        }
   }
   
    public PageReference Save()
    {
        
        Integer Imonth;
        Boolean fHaveRecord = false; //set flag
        Boolean existRecord = false; //set flag
        
        if(Overdate == true)
        {
            return null;
        }
        Date Dtoday = Date.today();
        
        if(Dtoday.month() == 12){
            Imonth = 1;
        }
        else{
            Imonth = Dtoday.month() + 1;
        }
        
        Integer Iyear = Dtoday.year();
        if(Dtoday.month() == 12){ 
            Iyear++;
        }        
        String Smonth = String.valueOf(Imonth);
        String Syear = String.valueOf(Iyear);
                  
        List<monthly_cooperation_plan_with_hospital__c> existRecordList = [select DaysOfRotation__c,Hospital__c,
                                                                hospital_class__c,FlagHospital__c,EFM_Rotation__c,Display__c,
                                                                Name,Id from monthly_cooperation_plan_with_hospital__c 
                                                                where OwnerId  =: UserInfo.getUserId() and Month__c =: Imonth and Year__c =: Syear]; 
        
        List<Hospital__c> MyHosList = [select Id,Name from Hospital__c where (OwnerId  =: UserInfo.getUserId() and Active__c =: true)
            or  (OwnerId  =: UserInfo.getUserId() and Active__c =: false and effectivedate__c <: date.today().addmonths(2).tostartofmonth())
             or (OwnerId  !=: UserInfo.getUserId() and effectivedate__c <: date.today().addmonths(2).tostartofmonth())];
        Map<Id, Hospital__c> MyHosMap = new Map<Id, Hospital__c>( MyHosList );
        
        Map<Id, monthly_cooperation_plan_with_hospital__c> InsertMap = new Map<Id, monthly_cooperation_plan_with_hospital__c>( );
        Map<Id, monthly_cooperation_plan_with_hospital__c> UpdateMap = new Map<Id, monthly_cooperation_plan_with_hospital__c>( );

        monthly_cooperation_plan_with_hospital__c updateRec = new monthly_cooperation_plan_with_hospital__c();

        if(RecordList != null)
        {
           for(AddMonthlyCooperationRecordItemControl mcpwh:RecordList) //loop from item list
            {            
                
                if(mcpwh.FhIsCheck == true){ //flag hospital is selected
                    mcpwh.planRecord.FlagHospital__c =  true;
                    fHaveRecord = true;
                }
                else{
                    mcpwh.planRecord.FlagHospital__c =  false;
                    fHaveRecord = true;                             
                }                            
                if(mcpwh.SsyIsCheck == true){ //EFM_Rotation__c is selected
                    mcpwh.planRecord.EFM_Rotation__c = true;
                    fHaveRecord = true;
                }
                else{
                    mcpwh.planRecord.EFM_Rotation__c = false;
                    fHaveRecord = true;                
                }
                if(mcpwh.DisIsCheck == true){ //Display is selected
                    mcpwh.planRecord.Display__c = true;             
                    fHaveRecord = true;
                }
                else{
                    mcpwh.planRecord.Display__c = false;             
                    fHaveRecord = true;                
                }
                
                if(mcpwh.DorIsCheck== true){ //days of rotation is keyed in.
                    mcpwh.planRecord.DaysOfRotation__c = true;                    
                    fHaveRecord = true;
                }
                else{
                    mcpwh.planRecord.DaysOfRotation__c = false;                    
                    fHaveRecord = true;                
                }
                
                if(fHaveRecord == false)
                {
                    continue;                 
                } 
                
                //Record is keyed in            
                monthly_cooperation_plan_with_hospital__c SaveRecord = new monthly_cooperation_plan_with_hospital__c();
                
                Hospital__c hName = MyHosMap.get(mcpwh.planRecord.Hospital__c); 
                mcpwh.planRecord.Name = hName.Name + Syear + '年'+ Smonth + '月'+'填报';
                
                mcpwh.planRecord.Month__c = Imonth; 
                mcpwh.planRecord.Year__c = Syear;              
                SaveRecord = mcpwh.planRecord; 
               
                for(monthly_cooperation_plan_with_hospital__c mcpForCheck : existRecordList )
                {
                    if(mcpForCheck.Hospital__c == SaveRecord.Hospital__c)
                    {
                        existRecord = true;
                        updateRec = mcpForCheck;
                        updateRec.FlagHospital__c = mcpwh.planRecord.FlagHospital__c;
                        updateRec.EFM_Rotation__c = mcpwh.planRecord.EFM_Rotation__c;
                        updateRec.Display__c = mcpwh.planRecord.Display__c;
                        updateRec.DaysOfRotation__c = mcpwh.planRecord.DaysOfRotation__c;
                        break;                      
                    }
                }

                
                //record is new, so insert record
                if(existRecord == false){              
                    if(mcpwh.haveRecord == true)
                    {
                        UpdateMap.put(updateRec.Hospital__c,updateRec);
                    }
                    else{
                        InsertMap.put(SaveRecord.Hospital__c,SaveRecord);                     
                    }
                }
                else{
                    UpdateMap.put(updateRec.Hospital__c,updateRec);
                    existRecord = false;
                }              
                fHaveRecord = false; //clear flag            
            }
            if(UpdateMap != null){
                if(UpdateMap.size() > 0){
                    update UpdateMap.values();
                }
            }
            if(InsertMap != null){
                if(InsertMap.size() > 0){
                    insert InsertMap.values();
                }
            }            
 
            //return page to Monthly Cooperation Plan        
            pageReference pr = new pageReference('/a0p/o');    
            pr.setredirect(true);      
            return pr;
        }
        return null;
    }

    static testMethod void AddMonthlyCooperationPlanControlTest()
    {
        Profile p  = [select id from profile where name = 'System Administrator'or name =: '系统管理员'];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', 
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='standarduser@testorg1.com');
        insert u1;
        
        Hospital__c hos = new Hospital__c();
        hos.Name = 'aaaaaaaa';
        hos.Active__c = true;
        hos.Nickname__c = 'aaaaaaaaaaa';
        hos.OwnerId = u1.Id;
        insert hos;    
    
        System.runAs(u1) {
            
            
            monthly_cooperation_plan_with_hospital__c mcpwh = new monthly_cooperation_plan_with_hospital__c();
            mcpwh.ownerid = u1.id;
            ApexPages.StandardController a=new ApexPages.StandardController(mcpwh);
            AddMonthlyCooperationPlanControl testCase = new AddMonthlyCooperationPlanControl(a);
            System.assert(testCase.UrlId == null);
            
            testCase.Save();     

            testCase.RecordList.get(0).FhIsCheck  = true;
            testCase.RecordList.get(0).SsyIsCheck = true;
            testCase.RecordList.get(0).DisIsCheck = true;
            testCase.RecordList.get(0).DorIsCheck = true;          
            
        
        }
    }
}